package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.constant.HttpStatus;
import com.crm.common.exception.base.BaseException;
import com.crm.common.result.AjaxResult;
import com.crm.common.result.PageResult;
import com.crm.common.utils.StringUtils;
import com.crm.common.utils.UserThreadLocal;
import com.crm.domain.Activity;
import com.crm.domain.Clue;
import com.crm.domain.Rule;
import com.crm.domain.User;
import com.crm.dto.CluePageQueryDto;
import com.crm.dto.GainClueDto;
import com.crm.mapper.ClueMapper;
import com.crm.service.ActivityService;
import com.crm.service.ClueService;
import com.crm.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    private final ActivityService activityService;

    private final UserService userService;

    private final ClueMapper clueMapper;

    private final RedisTemplate redisTemplate;

    @Override
    public PageResult pageClue(CluePageQueryDto dto) {
        Page<Clue> cluePage = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<Clue> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(dto.getId()!=null,Clue::getId,dto.getId());
        wrapper.like(StringUtils.isNotEmpty(dto.getPhone()),Clue::getPhone,dto.getPhone());
        wrapper.like(StringUtils.isNotEmpty(dto.getOwner()),Clue::getOwner,dto.getOwner());
        wrapper.eq(dto.getStatus()!=null,Clue::getStatus,dto.getStatus());
        wrapper.eq(dto.getChannel()!=null,Clue::getChannel,dto.getChannel());
        wrapper.in(Clue::getStatus,Clue.CLUE_STATUS_WAITING,Clue.CLUE_STATUS_FOLLOWING);
        wrapper.orderByDesc(Clue::getCreateTime);
        if(dto.getParams().get("beginTime")!=null && dto.getParams().get("beginTime")!=""
        && dto.getParams().get("endTime")!=null && dto.getParams().get("endTime")!=""){
            wrapper.between(Clue::getCreateTime,dto.getParams().get("beginTime"),dto.getParams().get("endTime"));
        }
        Page<Clue> page = super.page(cluePage, wrapper);
        PageResult pageResult = new PageResult();
        pageResult.setRows(page.getRecords());
        pageResult.setTotal(page.getTotal());
        pageResult.setMsg("查询成功");
        pageResult.setCode(HttpStatus.SUCCESS);
        return pageResult;
    }

    @Override
    public AjaxResult pageCluePool(CluePageQueryDto dto) {
        Page<Clue> cluePage = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<Clue> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(dto.getId()!=null,Clue::getId,dto.getId());
        wrapper.like(StringUtils.isNotEmpty(dto.getPhone()),Clue::getPhone,dto.getPhone());
        wrapper.eq(dto.getChannel()!=null,Clue::getChannel,dto.getChannel());
        wrapper.eq(Clue::getStatus,Clue.CLUE_STATUS_FALSE);
        if(dto.getParams().get("beginTime")!=null && dto.getParams().get("beginTime")!=""
                && dto.getParams().get("endTime")!=null && dto.getParams().get("endTime")!=""){
            wrapper.between(Clue::getCreateTime,dto.getParams().get("beginTime"),dto.getParams().get("endTime"));
        }
        Page<Clue> page = super.page(cluePage, wrapper);
        List<Clue> poolClues = page.getRecords();
        for (Clue poolClue : poolClues) {
            Activity activity = activityService.getById(poolClue.getActivityId());
            poolClue.setActivityName(activity.getName());
        }
        AjaxResult ajax = new AjaxResult();
        ajax.put("total", page.getTotal());
        ajax.put("rows", poolClues);
        ajax.put("code", HttpStatus.SUCCESS);
        return ajax;
    }

    @Override
    public void insertClue(Clue clue) {
        Long userId = UserThreadLocal.getUserId();
        int currentNum = clueMapper.countClueByUserId(userId);
        Integer maxNum = (Integer)redisTemplate.opsForValue().get(Rule.MAX_NUMBER_KEY + Rule.RULE_TYPE_CLUE);
        if(currentNum>=maxNum){
            throw new BaseException("保有量达到上限");
        }
        //todo 查询当前user持有数量是否到达最大
        User user = userService.getById(userId);
        clue.setOwner(user.getUserName());
        clue.setUserId(userId);
        clue.setOwnerTime(LocalDateTime.now());
        clue.setCreateTime(LocalDateTime.now());
        clue.setStatus(Clue.CLUE_STATUS_WAITING);
        clue.setLevel(Clue.CLUE_LEVEL_WATCHING);
        super.save(clue);
    }

    @Override
    public AjaxResult gainClue(GainClueDto dto) {
        List<Clue> clues = super.listByIds(dto.getIds());
        int currentNum = clueMapper.countClueByUserId(dto.getUserId());
        log.info("当前持有量: {}",currentNum);
        Integer maxNum = (Integer)redisTemplate.opsForValue().get(Rule.MAX_NUMBER_KEY + Rule.RULE_TYPE_CLUE);
        if(currentNum>=maxNum){
            return new AjaxResult(HttpStatus.ERROR,"当前保有量已经达到上限");
        }else {
            if(currentNum+dto.getIds().size()>maxNum){
                return AjaxResult.error("保有量达到上限,最多选择"+(maxNum-currentNum)+"条数据");
            }
            for (Clue clue : clues) {
                clue.setUserId(dto.getUserId());
                User user = userService.getById(dto.getUserId());
                clue.setOwner(user.getUserName());
                clue.setOwnerTime(LocalDateTime.now());
                clue.setStatus(Clue.CLUE_STATUS_WAITING);
            }
            super.saveBatch(clues);
        }
        return new AjaxResult();
    }
}
